import pandas as pd
import matplotlib.pyplot as plt

# 设置中文字体和图表清晰度
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['figure.dpi'] = 300

# 读取Excel文件
try:
    df = pd.read_excel('c:/Users/86183/Desktop/新建文件夹/FhjlViewDD.xlsx')
    
    # 检查必要列是否存在
    required_columns = ['创建时间', '发货地', '净重']
    for col in required_columns:
        if col not in df.columns:
            raise ValueError(f'Excel文件中缺少必要的列: {col}')
    
    # 转换创建时间列为datetime类型
    df['创建时间'] = pd.to_datetime(df['创建时间'])
    
    # 筛选6月份的数据
    df_june = df[df['创建时间'].dt.month == 6]
    
    # 按发货地分组汇总净重数据
    location_summary = df_june.groupby('发货地')['净重'].sum().sort_values(ascending=False)
    
    # 绘制饼状图
    plt.figure(figsize=(12, 8))
    
    # 只显示前5大发货地，其余归为"其他"
    top_locations = location_summary.head(5)
    other_locations = pd.Series({
        '其他': location_summary[5:].sum()
    })
    pie_data = pd.concat([top_locations, other_locations])
    
    # 绘制饼图（不显示百分比标签）
    wedges = plt.pie(pie_data, 
                   labels=None, 
                   startangle=90)[0]
    
    # 计算百分比并添加到图例标签
    percentages = [f'{100*x/sum(pie_data):.1f}%' for x in pie_data]
    legend_labels = [f'{label} ({percent})' for label, percent in zip(pie_data.index, percentages)]
    
    # 添加带百分比的图例
    plt.legend(wedges, legend_labels,
              title='发货地及占比',
              loc='center left',
              bbox_to_anchor=(1, 0.5),
              fontsize=8)
    plt.title('6月份各发货地发货总量占比')
    
    # 保存图表
    plt.savefig('c:/Users/86183/Desktop/新建文件夹/发货地发货总量饼图.png')
    plt.show()
    
    # 保存统计结果到CSV
    pie_data.to_csv('c:/Users/86183/Desktop/新建文件夹/shipping_location_summary.csv')
    print('统计完成，图表已保存为"发货地发货总量饼图.png"，数据已保存为"shipping_location_summary.csv"')
    
except FileNotFoundError:
    print('未找到指定的Excel文件，请检查文件路径。')
except Exception as e:
    print(f'处理过程中出现错误: {e}')
